package com.walkline.screen;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.m2g.SVGImage;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.PNGEncodedImage;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.FontManager;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

import com.walkline.app.WeatherAppConfig;
import com.walkline.util.Enumerations.IconSize;
import com.walkline.util.Enumerations.PlaceType;
import com.walkline.util.Function;
import com.walkline.util.StringUtility;
import com.walkline.util.ui.ForegroundManager;
import com.walkline.util.ui.ListStyleButtonField;
import com.walkline.util.ui.ListStyleButtonSet;
import com.walkline.weather.WeatherException;
import com.walkline.weather.WeatherSDK;
import com.walkline.weather.inf.Forecast;
import com.walkline.weather.inf.Place;
import com.walkline.weather.inf.Places;
import com.walkline.weather.inf.Weather;

public final class WeatherScreen extends MainScreen
{
	WeatherSDK _weather;
	BitmapField _bitmapField;
	EditField _queryField;
	VerticalFieldManager _vfm = new VerticalFieldManager(VERTICAL_SCROLL | VERTICAL_SCROLLBAR | USE_ALL_HEIGHT);
	ForegroundManager _foreground = new ForegroundManager(0);
	ListStyleButtonSet _placesSet = new ListStyleButtonSet();

    public WeatherScreen()
    {
    	super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		try {
			FontFamily family = FontFamily.forName("BBGlobal Sans");
			Font appFont = family.getFont(Font.PLAIN, 8, Ui.UNITS_pt);
			FontManager.getInstance().setApplicationFont(appFont);
		} catch (ClassNotFoundException e) {}

		//String titleIconName = Display.getWidth() < 640 ? "icon.png" : "icon.png";
		//BitmapField bmpTitleField = new BitmapField(Bitmap.getBitmapResource(titleIconName));
		//bmpTitleField.setSpace(5, 5);
		LabelField labelTitleField = new LabelField(WeatherAppConfig.APP_TITLE, LabelField.ELLIPSIS);
		labelTitleField.setFont(WeatherAppConfig.FONT_MAIN_TITLE);

		HorizontalFieldManager hfm = new HorizontalFieldManager(USE_ALL_WIDTH);
		VerticalFieldManager vfm1 = new VerticalFieldManager(FIELD_VCENTER);
		vfm1.add(labelTitleField);
		//hfm.add(bmpTitleField);
		hfm.add(vfm1);
		hfm.setBackground(WeatherAppConfig.bgColor_Gradient);
		setTitle(hfm);

        //setBackground(BackgroundFactory.createSolidBackground(Color.BLUE));

        ButtonField searchWOEID = new ButtonField("Search for WOEID", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
        ButtonField showSVG = new ButtonField("Show SVG", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
        _queryField = new EditField("输入查询条件：", "", EditField.DEFAULT_MAXCHARS, EditField.USE_ALL_WIDTH | EditField.NO_NEWLINE);
        _bitmapField = new BitmapField();

        //ListStyleButtonSet set = new ListStyleButtonSet();
        //ListStyleButtonField item = new ListStyleButtonField(Function.getUpdateHomeScreenIcon(showSVG2BMP()));

        //set.add(item);

        //add(showSVG);
        //add(bitmapField);
        //add(set);
        add(_queryField);
        add(searchWOEID);
        _placesSet.setMargin(0, 0, 0, 0);
        _foreground.add(_placesSet);
        _vfm.add(_foreground);
        add(_vfm);

        searchWOEID.setChangeListener(new FieldChangeListener()
        {
			public void fieldChanged(Field field, int context)
			{
				searchWOEID();
			}
		});
        showSVG.setChangeListener(new FieldChangeListener()
        {
			public void fieldChanged(Field field, int context)
			{
				showSVG2PNG();
			}
		});

        _weather = WeatherSDK.getInstance();
    }

    private void searchWOEID()
    {
    	String queryValue = _queryField.getText();

		if (queryValue.trim().equalsIgnoreCase(""))
		{
			_queryField.setText("");
			_queryField.setFocus();
			Function.errorDialog("Query field empty!");

			return;
		}

		if (StringUtility.hasInvalidCharacters(queryValue))
		{
			_queryField.setText("");
			_queryField.setFocus();
			Function.errorDialog("Include invalid character, please don't input the following characters:\n\n,()*!@#$&=|;:?/");

			return;
		}

		//queryValue = StringUtility.replaceSpaceCharactersToHTML(queryValue);

		try {
			Places places = _weather.getPlaces(queryValue);
			//Places places = new YahooPlaces(_weather, new StringBuffer(getClass().getResourceAsStream("/xml/places_tianjin.xml").toString()));

			if (places == null) {return;}

			if (_placesSet.getFieldCount() > 0) {_placesSet.deleteAll();}

			ListStyleButtonField item;
			for (int i=0; i<places.getCount(); i++)
			{
				final Place place = (Place) places.getPlaces().elementAt(i);

				if (place.getPlaceTypeCode().equalsIgnoreCase(PlaceType.WOE_TOWN))
				{
					item = new ListStyleButtonField(place);
					item.setChangeListener(new FieldChangeListener()
					{
						public void fieldChanged(Field field, int context)
						{
							getRssFeed(place.getWOEID());
						}
					});
					_placesSet.add(item);
				}
			}

			if (_placesSet.getFieldCount() <= 0)
			{
				_placesSet.add(new LabelField("(无)", LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH));
				return;
			}

			/*
			vfm.deleteAll();
			vfm.add(new EditField("Start: ", String.valueOf(places.getStart())));
			vfm.add(new EditField("Count: ", String.valueOf(places.getCount())));
			vfm.add(new EditField("Total: ", String.valueOf(places.getTotal())));

			for (int i=0; i<places.getCount(); i++)
			{
				Place place = (Place) places.getPlaces().elementAt(i);

				vfm.add(new MyTitleLabelField(place.getName()));
				vfm.add(new EditField("WOEID: ", place.getWOEID()));
				vfm.add(new LabelField("Place Type"));
				vfm.add(new EditField("----Name: ", place.getPlaceTypeName()));
				vfm.add(new EditField("----Code: ", place.getPlaceTypeCode()));
				vfm.add(new EditField("Name: ", place.getName()));
				vfm.add(new EditField("Country: ", place.getCountry()));
				vfm.add(new EditField("----Type: ", place.getCountryType()));
				vfm.add(new EditField("----Code: ", place.getCountryCode()));
				vfm.add(new EditField("----WOEID: ", place.getCountryWOEID()));
				vfm.add(new EditField("Admin1: ", place.getAdmin1()));
				vfm.add(new EditField("----Type: ", place.getAdmin1Type()));
				vfm.add(new EditField("----Code: ", place.getAdmin1Code()));
				vfm.add(new EditField("----WOEID: ", place.getAdmin1WOEID()));
				vfm.add(new EditField("Admin2: ", place.getAdmin2()));
				vfm.add(new EditField("----Type: ", place.getAdmin2Type()));
				vfm.add(new EditField("----Code: ", place.getAdmin2Code()));
				vfm.add(new EditField("----WOEID: ", place.getAdmin2WOEID()));
				vfm.add(new EditField("Admin3: ", place.getAdmin3()));
				vfm.add(new EditField("----Type: ", place.getAdmin3Type()));
				vfm.add(new EditField("----Code: ", place.getAdmin3Code()));
				vfm.add(new EditField("----WOEID: ", place.getAdmin3WOEID()));
				vfm.add(new EditField("Locality1: ", place.getLocality1()));
				vfm.add(new EditField("----Type: ", place.getLocality1Type()));
				vfm.add(new EditField("----WOEID: ", place.getLocality1WOEID()));
				vfm.add(new EditField("Locality2: ", place.getLocality2()));
				vfm.add(new EditField("----Type: ", place.getLocality2Type()));
				vfm.add(new EditField("----WOEID: ", place.getLocality2WOEID()));
				vfm.add(new EditField("Postal: ", place.getPostal()));
				vfm.add(new EditField("----Type: ", place.getPostalType()));
				vfm.add(new EditField("----WOEID: ", place.getPostalWOEID()));
				vfm.add(new LabelField("Centroid"));
				vfm.add(new EditField("----Latitude: ", place.getCentroidLatitude()));
				vfm.add(new EditField("----Longitude: ", place.getCentroidLongitude()));
				vfm.add(new LabelField("SouthWest"));
				vfm.add(new EditField("----Latitude: ", place.getSouthWestLatitude()));
				vfm.add(new EditField("----Longitude: ", place.getSouthWestLongitude()));
				vfm.add(new LabelField("NorthEast"));
				vfm.add(new EditField("----Latitude: ", place.getNorthEastLatitude()));
				vfm.add(new EditField("----Longitude: ", place.getNorthEastLongitude()));
				vfm.add(new EditField("AreaRank: ", place.getAreaRank()));
				vfm.add(new EditField("PopRank: ", place.getPopRank()));
				vfm.add(new EditField("Timezone: ", place.getTimezone()));
				vfm.add(new EditField("----Type: ", place.getTimezoneType()));
				vfm.add(new EditField("----WOEID: ", place.getTimezoneWOEID()));
			} */
		} catch (WeatherException e) {Function.errorDialog(e.toString());}
    }

    private void getRssFeed(String woeid)
    {
        try {
			Weather weather = _weather.getWeather(woeid, "c");

			if (weather == null) {return;}

			_vfm.deleteAll();
			_vfm.add(new EditField("Title: ", weather.getTitle()));
			_vfm.add(new EditField("Link: ", weather.getLink()));
			_vfm.add(new EditField("Description: ", weather.getDescription()));
			_vfm.add(new EditField("Language: ", weather.getLanguage()));
			_vfm.add(new EditField("Last build date: ", weather.getLastBuildDate()));
			_vfm.add(new EditField("TTL: ", weather.getTTL()));
			_vfm.add(new MyTitleLabelField("Location"));
			_vfm.add(new EditField("Country: ", weather.getLocationCountry()));
			_vfm.add(new EditField("Region: ", weather.getLocationRegion()));
			_vfm.add(new EditField("City: ", weather.getLocationCity()));
			_vfm.add(new MyTitleLabelField("Units"));
			_vfm.add(new EditField("Speed: ", weather.getUnitsSpeed()));
			_vfm.add(new EditField("Distance: ", weather.getUnitsDistance()));
			_vfm.add(new EditField("Pressure: ", weather.getUnitsPressure()));
			_vfm.add(new EditField("Temperature: ", weather.getUnitsTemperature()));
			_vfm.add(new MyTitleLabelField("Wind"));
			_vfm.add(new EditField("Chill: ", weather.getWindChill()));
			_vfm.add(new EditField("Direction: ", weather.getWindDirection()));
			_vfm.add(new EditField("Speed: ", weather.getWindSpeed()));
			_vfm.add(new MyTitleLabelField("Atmosphere"));
			_vfm.add(new EditField("Humidity: ", weather.getAtmosphereHumidity()));
			_vfm.add(new EditField("Pressure: ", weather.getAtmospherePressure()));
			_vfm.add(new EditField("Visibility: ", weather.getAtmosphereVisibility()));
			_vfm.add(new EditField("Rising: ", weather.getAtmosphereRising()));
			_vfm.add(new MyTitleLabelField("Astronomy"));
			_vfm.add(new EditField("Sunrise: ", weather.getAstronomySunrise()));
			_vfm.add(new EditField("Sunset: ", weather.getAstronomySunset()));
			_vfm.add(new MyTitleLabelField("Image"));
			_vfm.add(new EditField("Title: ", weather.getImageTitle()));
			_vfm.add(new EditField("Link: ", weather.getImageLink()));
			_vfm.add(new EditField("Url: ", weather.getImageUrl()));
			_vfm.add(new EditField("Width: ", weather.getImageWidth()));
			_vfm.add(new EditField("Height: ", weather.getImageHeight()));
			_vfm.add(new MyTitleLabelField("Item"));
			_vfm.add(new EditField("Title: ", weather.getItemTitle()));
			_vfm.add(new EditField("Link: ", weather.getItemLink()));
			_vfm.add(new EditField("Description: ", weather.getItemDescription()));
			_vfm.add(new EditField("Pub date: ", weather.getItemPubDate()));
			_vfm.add(new EditField("Geo.Lat: ", weather.getItemGeoLat()));
			_vfm.add(new EditField("Geo.Long: ", weather.getItemGeoLong()));
			_vfm.add(new EditField("Guid: ", weather.getItemGuid()));
			_vfm.add(new MyTitleLabelField("Condition"));
			_vfm.add(new EditField("Date: ", weather.getConditionDate()));
			_vfm.add(new EditField("Temp: ", weather.getConditionTemp()));
			_vfm.add(new EditField("Code: ", weather.getConditionCode()));
			_vfm.add(new EditField("Text: ", weather.getConditionText()));

			_vfm.add(new MyTitleLabelField("Forecast"));

			Vector forecasts = weather.getForecasts();
			for (int i=0; i<forecasts.size(); i++)
			{
				Forecast forecast = (Forecast) forecasts.elementAt(i);

				_vfm.add(new MyTitleLabelField(forecast.getDay()));
				_vfm.add(new EditField("Day: ", forecast.getDay()));
				_vfm.add(new EditField("Date: ", forecast.getDate()));
				_vfm.add(new EditField("Code: ", forecast.getCode()));
				_vfm.add(new EditField("Text: ", forecast.getText()));
				_vfm.add(new EditField("High: ", forecast.getHigh()));
				_vfm.add(new EditField("Low: ", forecast.getLow()));
			}
		} catch (WeatherException e) {Function.errorDialog(e.toString());}
    }

    private void showSVG2PNG()
    {
    	SVGImage _svgImage = null;

    	InputStream input = getClass().getResourceAsStream("/sun.svg");
    	try {
			_svgImage = (SVGImage) SVGImage.createImage(input, null);
			PNGEncodedImage _pngImage = Function.GetPNGImage(_svgImage, IconSize.MEDIUM);

			_bitmapField.setBitmap(_pngImage.getBitmap());
		} catch (IOException e) {Function.errorDialog(e.toString());}
    }

    private Bitmap showSVG2BMP()
    {
    	SVGImage _svgImage = null;
    	PNGEncodedImage _pngImage = null;

    	InputStream input = getClass().getResourceAsStream("/sun.svg");
    	try {
			_svgImage = (SVGImage) SVGImage.createImage(input, null);
			_pngImage = Function.GetPNGImage(_svgImage, IconSize.LARGE);
		} catch (IOException e) {Function.errorDialog(e.toString());}

    	return _pngImage.getBitmap();
    }

    protected boolean onSavePrompt() {return true;}

    class MyTitleLabelField extends LabelField
	{
		public MyTitleLabelField(String text) {super(text, USE_ALL_WIDTH | LabelField.ELLIPSIS);}

		protected void paintBackground(Graphics g) {
			g.setColor(Color.GRAY);
			g.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8);
			super.paintBackground(g);
		}

		protected void paint(Graphics g)
		{
			g.setColor(Color.BLACK);
			super.paint(g);	
		}
	}
}